<?php

namespace app\popo\dto;

use app\popo\vo\Required;
use support\exception\BusinessException;

class BaseDto
{
    protected function validateRequired(): void
    {
        $ref = new \ReflectionClass($this);
        foreach ($ref->getProperties() as $property) {
            // Required 注解校验
            $requiredAttributes = $property->getAttributes(\app\popo\vo\Required::class);
            if ($requiredAttributes) {
                $property->setAccessible(true);
                $value = $property->getValue($this);
                $required = $requiredAttributes[0]->newInstance();
                if (empty($value)) {
                    throw new BusinessException($property->getName() . ' 不能为空', 0);
                }
                if (is_string($value)) {
                    $len = mb_strlen($value);
                    if ($required->min > 0 && $len < $required->min) {
                        throw new BusinessException($property->getName() . ' 长度不能小于' . $required->min, 0);
                    }
                    if ($required->max > 0 && $len > $required->max) {
                        throw new BusinessException($property->getName() . ' 长度不能大于' . $required->max, 0);
                    }
                }
            }
            // BelongsTo 注解校验
            $belongsToAttributes = $property->getAttributes(\app\popo\vo\BelongsTo::class);
            if ($belongsToAttributes) {
                $property->setAccessible(true);
                $value = $property->getValue($this);
                $belongsTo = $belongsToAttributes[0]->newInstance();
                if ($value !== null && !is_a($value, $belongsTo->className)) {
                    throw new BusinessException($property->getName() . ' 必须归属于 ' . $belongsTo->className, 0);
                }
            }
        }
    }
}